package lab3;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class GuessServlet
 */
@WebServlet("/lab3/guess")
public class GuessServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		NumberGuess numberGuess = (NumberGuess) session.getAttribute("guess");

		if (numberGuess == null) {
			numberGuess = new NumberGuess();
			session.setAttribute("guess", numberGuess);
		}

		numberGuess.guess(request.getParameter("guess"));
		if (numberGuess.isSuccess()) {
			request.getRequestDispatcher("/lab3/Done.jsp").forward(request,
					response);
		} else {
			request.getRequestDispatcher("/lab3/Again.jsp").forward(request,
					response);
		}
	}

}
